package com.fishingwithme.android.ui.screens.harvest

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.stringResource
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.paging.LoadState
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemKey
import coil.compose.AsyncImage
import com.fishingwithme.android.R
import com.fishingwithme.android.data.model.HarvestRecordDto
import com.fishingwithme.android.navigation.FishingNavigation
import com.fishingwithme.android.ui.theme.AppDimensions
import com.fishingwithme.android.ui.viewmodels.HarvestListViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HarvestListScreen(
    navController: NavController,
    spotId: String,
    viewModel: HarvestListViewModel = hiltViewModel()
) {
    viewModel.setSpotId(spotId)
    val harvestRecords = viewModel.getHarvestRecords().collectAsLazyPagingItems()

    Scaffold(
    ) { paddingValues ->
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {
            LazyColumn(
                contentPadding = PaddingValues(AppDimensions.SPACING_16),
                verticalArrangement = Arrangement.spacedBy(AppDimensions.SPACING_8) // Reduced space between rows
            ) {
                items(
                    count = harvestRecords.itemCount,
                    key = harvestRecords.itemKey { it.id }
                ) { index ->
                    harvestRecords[index]?.let { record ->
                        if (index % 2 == 0) {
                            // Even index - create a new row
                            Row(
                                modifier = Modifier.fillMaxWidth(),
                                horizontalArrangement = Arrangement.spacedBy(AppDimensions.SPACING_8) // Reduced space between cards
                            ) {
                                // First item in the row
                                Box(modifier = Modifier.weight(1f)) {
                                    HarvestRecordItem(record = record, navController)
                                }

                                // Second item in the row (if exists)
                                val nextIndex = index + 1
                                if (nextIndex < harvestRecords.itemCount) {
                                    harvestRecords[nextIndex]?.let { nextRecord ->
                                        Box(modifier = Modifier.weight(1f)) {
                                            HarvestRecordItem(record = nextRecord, navController)
                                        }
                                    } ?: Box(modifier = Modifier.weight(1f))
                                } else {
                                    Box(modifier = Modifier.weight(1f))
                                }
                            }
                        }
                    }
                }

                harvestRecords.apply {
                    when {
                        loadState.refresh is LoadState.Loading -> {
                            item {
                                Box(
                                    modifier = Modifier.fillMaxWidth(),
                                    contentAlignment = Alignment.Center
                                ) {
                                    CircularProgressIndicator()
                                }
                            }
                        }

                        loadState.append is LoadState.Loading -> {
                            item {
                                Box(
                                    modifier = Modifier.fillMaxWidth(),
                                    contentAlignment = Alignment.Center
                                ) {
                                    CircularProgressIndicator()
                                }
                            }
                        }

                        loadState.refresh is LoadState.Error -> {
                            val error = loadState.refresh as LoadState.Error
                            item {
                                Text(
                                    text = stringResource(R.string.error_load_failed) + ": ${error.error.message}",
                                    color = MaterialTheme.colorScheme.error,
                                    modifier = Modifier.fillMaxWidth()
                                )
                            }
                        }

                        loadState.append is LoadState.Error -> {
                            val error = loadState.append as LoadState.Error
                            item {
                                Text(
                                    text = stringResource(R.string.error_load_failed) + ": ${error.error.message}",
                                    color = MaterialTheme.colorScheme.error,
                                    modifier = Modifier.fillMaxWidth()
                                )
                            }
                        }
                    }
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HarvestRecordItem(record: HarvestRecordDto, navController: NavController) {
    Card(
        modifier = Modifier,
        elevation = CardDefaults.cardElevation(defaultElevation = AppDimensions.CARD_ELEVATION_2),
        onClick = {
            navController.navigate("${FishingNavigation.SHOW}?id=${record.id}")
        }

    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(AppDimensions.CARD_HEIGHT_267) // 200 + 200/3 = 267 dp
        ) {
            // Big picture that fully covers the card
            if (record.jsonHisPictures.isNotEmpty()) {
                AsyncImage(
                    model = record.jsonHisPictures.firstOrNull(),
                    contentDescription = "Harvest image",
                    modifier = Modifier
                        .fillMaxSize(),
                    contentScale = ContentScale.Crop
                )
            } else {
                // Placeholder if no image - using theme-appropriate colors
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(MaterialTheme.colorScheme.surfaceVariant)
                ) {
                    Text(
                        text = stringResource(R.string.error_unknown),
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.align(Alignment.Center)
                    )
                }
            }

            // Fishes text overlay on the picture with theme-appropriate colors
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(AppDimensions.ICON_SIZE_48)
                    .align(Alignment.TopCenter)
                    .background(MaterialTheme.colorScheme.primary.copy(alpha = 0.7f))
            ) {
                Text(
                    text = stringResource(R.string.harvest_type) + ": ${record.fishes.joinToString(", ") { it.name }}",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onPrimary,
                    modifier = Modifier
                        .align(Alignment.CenterStart)
                        .padding(start = AppDimensions.SPACING_8)
                )
            }

            // Bottom section with user info - using theme-appropriate colors
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(AppDimensions.CARD_HEIGHT_48)
                    .align(Alignment.BottomCenter)
                    .background(MaterialTheme.colorScheme.surface.copy(alpha = 0.8f))
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(AppDimensions.SPACING_8),
                    verticalArrangement = Arrangement.SpaceBetween
                ) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.Start
                    ) {
                        Text(
                            text = record.nickName,
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurface
                        )

                        Spacer(modifier = Modifier.width(AppDimensions.SPACING_4))

                        Text(
                            text = if (record.isRec == 1) stringResource(R.string.recommended) else stringResource(
                                R.string.not_recommended
                            ),
                            style = MaterialTheme.typography.bodySmall,
                            color = if (record.isRec == 1) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.error
                        )
                        Spacer(modifier = Modifier.width(AppDimensions.SPACING_4))
                        Text(
                            text = stringResource(R.string.score_label) + ": ${record.scoreVal.name}",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurface
                        )
                    }
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = formatDate(record.fishingAt),
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
            }
        }
    }
}

// Helper function to format date as YYYY-MM-DD
fun formatDate(dateString: String): String {
    return try {
        // Parse the date string (assuming ISO format like "2025-09-08T04:38:32.540Z")
        val date = java.text.SimpleDateFormat(
            "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
            java.util.Locale.getDefault()
        )
            .parse(dateString)
        // Format as YYYY-MM-DD
        java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.getDefault()).format(date)
    } catch (e: Exception) {
        dateString.take(10)
    }
}